//
//  WBEmoticonStatckView.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/13.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit

protocol EmoticonStatckViewDelegate:NSObjectProtocol {

    func didEmoticonSelectedSecion(type:EmoticonStatckType)

}
enum EmoticonStatckType: Int {

    case Recent = 10000
    case Default = 10001
    case Emoji = 10002
    case Lxh = 10003

}


@available(iOS 9.0, *)
class WBEmoticonStatckView: UIStackView {

    //MARK: - 定义代理
    weak  var delegate: EmoticonStatckViewDelegate?
    
    var clickButton: UIButton?
  
   override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    
       //设置垂直还是水平
     axis = UILayoutConstraintAxis.Horizontal
    
      //填充效果
    distribution = .FillEqually
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    
    
   private func setupUI() {
    
     childButton(.Recent, title: "最近")
    childButton(.Default, title: "默认")
    childButton(.Emoji, title: "emoji")
    childButton(.Lxh, title: "浪小花")
    
    }
    
    
  private  func childButton(type:EmoticonStatckType,title:String) {
    
    let button = UIButton(type: UIButtonType.Custom)
    
    //设置选中效果和不选中效果
    button.setBackgroundImage(UIImage(named: "compose_emotion_table_normal"), forState: UIControlState.Normal)
    
    button.setBackgroundImage(UIImage(named: "compose_emotion_table_selected"), forState: UIControlState.Selected)
    
    button.addTarget(self, action: "showSelectedEmoticon:", forControlEvents: UIControlEvents.TouchUpInside)
    
    //需要区分button 给它添加tag 转换为rawValue
    button.tag = type.rawValue
    
    //设置文字和字体大小
    button.setTitle(title, forState: UIControlState.Normal)
    button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
    
    button.titleLabel?.font = UIFont.systemFontOfSize(14)
    
    //把需要添加的按钮 添加在addArrangsubview方法中 系统自动布局
    addArrangedSubview(button)
    
    
    if type == .Default {
        //默认点击
       button.selected = true
       clickButton = button
    
    }
    }

//    MARK: - footview按钮点击方法 调用代理
   @objc private func  showSelectedEmoticon(button:UIButton) {
    if button == clickButton {
      return
    }
     button.selected = !button.selected
    clickButton?.selected = false
    //记录点击
    clickButton = button
      //点击选择时调用代理
   delegate?.didEmoticonSelectedSecion(EmoticonStatckType(rawValue: button.tag)!)
    }
    
    //滑动cell实现切换
    func showSelectedButton(section:Int) {
      let button = viewWithTag(10000 + section) as! UIButton
        
        if button == clickButton {
          return
        }
        
        button.selected = true
        //原来的按钮选中效果消失
        clickButton?.selected = false
        clickButton = button
    }
    
    
//    MARK: - 懒加载

}
